import numpy as np
import statistics
import pickle
import scipy
from matplotlib import pyplot as plt

data=np.genfromtxt('DropletTest.dat',delimiter="  ",dtype=None)
tpoints,vars=data.shape

dropstart=0
dropdataraw=np.array([0,0,0,0], dtype=None)
j=0
r=0
dropdata=np.array([[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]],dtype=None)
dropperiod=0
rawanisotropy=0
threshold=1

for i in range(tpoints):
    if data[i][1] > threshold:
        dropstart=1
        if r==0:
            dropdataraw=[[0,0,0,0],data[i][:]]
            #print(dropdataraw)
            r=r+1
        else:
            current=data[i][:]
            dropdataraw=np.append(dropdataraw,[current],axis=0)
        r=r+1
    else:
        if dropstart==1:
            dropstart=0
            #print(dropdataraw)
            dropdataraw=np.delete(dropdataraw,0,0)
            droptime,vars=dropdataraw.shape

            PMT1=dropdataraw.T[1]
            PMT2=dropdataraw.T[2]
            Anni=dropdataraw.T[3]
            max=np.amax(PMT1)
            PMTthresh=max-0.1
            PMT1val=PMT1[PMT1>PMTthresh]
            average1=np.mean(PMT1val,dtype=None)
            dropstdv1=np.std(PMT1val,dtype=None)
            PMT2val=PMT2[PMT1>PMTthresh]
            average2=np.mean(PMT2val,dtype=None)
            dropstdv2=np.std(PMT2val,dtype=None)
            Annival=Anni[PMT1>PMTthresh]
            averageanni=np.mean(Annival,dtype=None)
            dropstdvanni=np.std(Annival,dtype=None)
            anical=(average1-average2)/(average1+2*average2)

            dropdata=np.append(dropdata,[[droptime,average1,dropstdv1,average2,dropstdv2,averageanni,dropstdvanni,anical]],axis=0)
            j=j+1
            r=0
            #print(dropdata)

PMT1=data.T[1]
time=data.T[0]
rawPMT1=PMT1[PMT1>1]
averagePMT1=np.average(rawPMT1)
stdvPMT1=np.std(rawPMT1)
yf=scipy.fft.fft(PMT1)
N=len(yf)
n=np.arange(N)
T=N/100
freq=n/T
FT=np.abs(yf)
print(FT)
print(freq)
FFT=np.append([FT],[freq],axis=0)

plt.plot(freq,FT)
plt.show


print("done")
np.savetxt('dropdata.txt', dropdata, delimiter = ',')
np.savetxt('PMT1.txt', rawPMT1, delimiter = ',')
np.savetxt('PMT1_stats.txt', [averagePMT1,stdvPMT1], delimiter = ',')
np.savetxt('FFT.txt',FFT, delimiter = ',')
